/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cis;

import java.sql.ResultSet;
import javax.swing.event.TableModelEvent;
import javax.swing.table.AbstractTableModel;

//this class manages the data in the product table in Products view
class CisProductTableModel extends AbstractTableModel {
    
    //store column names
    static String[] columnNames = new String[]{
        "Product ID", 
        "Product Name", 
        "Comment"};
    //store all product details
    static ResultSet data = initialize();
    
    //initialize the data field
    static ResultSet initialize() {
        try {
            return CisDatabase.getAllProducts();
        } catch (Exception ex) {
            return null;
        }
    }

    //get the number of rows of the data field
    public int getRowCount() {
        try {
            return CisDatabase.getResulSetRowCount(data);
        } catch (Exception ex) {
            return 0;
        }
    }

    //get the number of columns of the data field
    public int getColumnCount() {
        try {
            return CisDatabase.getResulSetColumnCount(data);
        } catch (Exception ex) {
            return 0;
        }
    }

    //get the value of the data field at (rowIndex, columnIndex)
    public Object getValueAt(int rowIndex, int columnIndex) {
        try {
            return CisDatabase.getResultSetValue(data, rowIndex + 1, columnIndex + 1);
        } catch (Exception ex) {
            return new Object();
        }
    }

    //get column name at index i
    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }

    // get the type of the values in the column at index columnIndex
    @Override
    public Class<?> getColumnClass(int columnIndex) {
        try {
            return CisDatabase.getResultSetValue(data, 1, columnIndex + 1).getClass();
        } catch (Exception ex) {
            return (new Object()).getClass();
        }
    }

    //when a row is inserted, display the new table
    public void fireRowsInsertedEvent() {
        fireTableRowsInserted(0, getRowCount() - 1);
    }
    
    //when a row is updated, display the new table
    public void fireRowsUpdatedEvent() {
        fireTableRowsUpdated(0, getRowCount() - 1);
    }
    
    //when a row is deleted, display the new table
    public void fireRowsDeletedEvent() {
        fireTableChanged(new TableModelEvent(this));
    }
}
